package com.woniuxy.cloud.userassembly.apiimpl;


import com.woniuxy.cloud.api.UserQueryAPI;
import com.woniuxy.cloud.api.dto.LoginDto;
import com.woniuxy.cloud.api.dto.RoleDto;
import com.woniuxy.cloud.api.dto.UserDto;
import com.woniuxy.cloud.api.param.DepositLevelParam;
import com.woniuxy.cloud.api.param.RoleIdAndAreaParam;

import com.woniuxy.cloud.demo.Result;
import com.woniuxy.cloud.dto.BaseDto;
import com.woniuxy.cloud.userassembly.exception.UserException;
import com.woniuxy.cloud.userassembly.param.SaveUserParam;
import com.woniuxy.cloud.userassembly.param.SaveUserRoleParam;
import com.woniuxy.cloud.userassembly.param.UpdateMyselfParam;
import com.woniuxy.cloud.userassembly.param.UserPageAndByKeyParam;
import com.woniuxy.cloud.userassembly.service.SysResourceService;
import com.woniuxy.cloud.userassembly.service.UserService;
import com.woniuxy.cloud.userassembly.util.ValidatedUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 周川雄
 * @since 2022-01-26
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserQueryApIImpl implements UserQueryAPI {
    @Resource
    private UserService userService;
    @Resource
    private SysResourceService resourceService;
    @Resource
    private Environment environment;

    @GetMapping("getPort")
    public String getPort() {
        // 编程的方式获取到Request
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        String user = request.getHeader("user");
        log.info("user{}", user);
        //人工异常
//        int i=0/0;
//        throw new RuntimeException("我是一个异常");
        return environment.getProperty("local.server.port");
    }

    /**
     * 登录
     *
     * @param username
     * @return
     */
    @Override
    public LoginDto login(String username) {
        log.info("用户{}尝试登录", username);
        //登录
        LoginDto dto = userService.login(username);
        return dto;
    }

    @Override
    public UserDto findUserById(Integer userId) {

        return userService.findUserById(userId);
    }

    @Override
    public UserDto updateUserDepositLevel(DepositLevelParam param) {

        return userService.updateUserDepositLevel(param);
    }

    @Override
    public Result listUserByRoleIdAndArea(RoleIdAndAreaParam param) {
        //先判断角色
        List<UserDto> userDtos = userService.listUserByRoleIdAndArea(param);
        return Result.newInstance().setCode(200).setMsg("查询成功").setData(userDtos);
    }

    /**
     * 通过用户id查询角色
     *
     * @param userId
     * @return
     */
    @Override
    public Result<List<RoleDto>> findRoleByUserId(Integer userId) {

        return Result.newInstance().setCode(200).setMsg("查询成功").setData(userService.findRoleByUserId(userId));

    }

    @Override
    public List<String> selectResourceByUserId(Integer id) {
         List<String> strings = resourceService.selectResourceByUserId(id);
        System.out.println(strings);
        return strings;
    }


    /**
     * 添加新用户
     * 是否普通用户,0是普通用户,1不是普通用户
     *
     * @param sup
     * @param result
     * @return
     */
    @ApiOperation("添加新用户")
    @PostMapping("/SaveUser.do")
    public Result SaveUser(@RequestBody @Validated SaveUserParam sup, BindingResult result) {
        //参数验证
        ValidatedUtil.ValidatedException(result);
        UserDto dto = userService.SaveUser(sup);

        if (!StringUtils.isEmpty(dto)) return Result.newInstance().setCode(200).setMsg("添加成功").setData(dto);
        throw new UserException("添加新用户失败", 10400);
    }


    /**
     * 查询所有用户
     *
     * @param upp
     * @return
     */
    @ApiOperation("查询所有用户")
    @PostMapping("/listUsers.do")
    public Result listUsers(@RequestBody UserPageAndByKeyParam upp) {
        BaseDto<UserDto> pad = userService.listUsers(upp);
        return Result.newInstance().setCode(200).setMsg("查询成功").setData(pad);
    }

    /**
     * 修改用户绑定的角色授权
     *
     * @param arp
     * @return
     */
    @ApiOperation("修改用户绑定的角色授权")
    @PostMapping("/saveUserRole.do")
    public Result saveUserRole(@RequestBody SaveUserRoleParam arp) {
        if (userService.saveUserRole(arp)) return Result.newInstance().setCode(200).setMsg("授权成功");
        throw new UserException("角色授权失败", 10407);

    }

    /**
     * 批量删除用户(逻辑删除)
     *
     * @param ids
     * @return
     */
    @ApiOperation("批量删除用户(逻辑删除)")
    @PostMapping("/removeUserByIds.do")
    public Result removeUserByIds(@RequestBody List<Integer> ids) {
        if (userService.removeUserByIds(ids)) return Result.newInstance().setCode(200).setMsg("删除成功");
        throw new UserException("删除用户失败", 10410);
    }

    /**
     * 修改自己用户号码
     *
     * @param ump
     * @param result
     * @return
     */
    @ApiOperation("用户自己修改自己的数据")
    @PostMapping("/updateByMyself.do")
    public Result updateByMyself(@RequestBody @Validated UpdateMyselfParam ump, BindingResult result) {
        //参数验证
        ValidatedUtil.ValidatedException(result);
        if (userService.UpdateMyselfParam(ump)) {
            return Result.newInstance().setCode(200).setMsg("修改成功");
        }
        throw new UserException("角色修改失败", 10411);
    }
}

